package cn.ekuma.epos.android.finder;

import com.android.calculator2.Logic.OnReturnListener;
import com.lorentzos.flingswipe.SwipeFlingAdapterView;

import cn.ekuma.android.AdapterFactory;
import cn.ekuma.android.keyBoardinput.KeyBoradInputPanel;
import cn.ekuma.android.ui.scan.Intents;
import cn.ekuma.android.ui.scan.history.HistoryItem;
import cn.ekuma.android.ui.scan.history.HistoryManager;
import cn.ekuma.epos.android.Config;
import cn.ekuma.epos.datalogic.local.LocalDBHelper;
import cn.ekuma.epos.datalogic.local.dao.ProductDAO;
import cn.ekuma.epos.datalogic.util.ProductUtil;
import cn.ekuma.epos.ui.android.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Toast;

import java.util.ArrayList;


public class ProductDialyActivate extends Activity implements OnReturnListener {
	KeyBoradInputPanel inputPanel;
	//EditText productDialyTxt;
	private SharedPreferences prefs;
	private boolean isLocalModel;
	private HistoryManager historyManager;
	private LocalDBHelper localDbHelper;
	private ProductDAO productDAO;
	
	String lastCode;

    protected boolean isLotNumberModel;
    protected String matchPattern;
    ArrayList<String> al;
    private ArrayAdapter<String> arrayAdapter;
    private ArrayList<String> tempList;


    protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Window window = getWindow();
	    window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
	    
	    
		setContentView(R.layout.base_key_input_seach);
		inputPanel=(KeyBoradInputPanel) this.findViewById(R.id.inputView);
		//productDialyTxt= (EditText) this.findViewById(R.id.productDialyTxt);
		inputPanel.setInputListener(this);
		
		prefs = PreferenceManager.getDefaultSharedPreferences(this);
		isLocalModel=prefs.getBoolean(Config.KEY_DB_LOCALMODEL, false);
		
		historyManager = new HistoryManager(this);
	   
	    localDbHelper=new LocalDBHelper(this);
	    productDAO=new ProductDAO(localDbHelper);

        isLotNumberModel=prefs.getBoolean(Config.KEY_LOT_NUMBER,false);
        matchPattern=prefs.getString(Config.KEY_LOT_NUMBER_PATTERN,"\\d*");
        getActionBar().setDisplayHomeAsUpEnabled(true);


        SwipeFlingAdapterView flingContainer = (SwipeFlingAdapterView) findViewById(R.id.swipeflingView);
        al = new ArrayList<String>();
        tempList = new ArrayList<String>();
        //choose your favorite adapter
        arrayAdapter = new ArrayAdapter<String>(this, R.layout.item, R.id.helloText, tempList );

        //set the listener and the adapter
        flingContainer.setAdapter(AdapterFactory.inversion(arrayAdapter));
        flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
            @Override
            public void removeFirstObjectInAdapter() {
                // this is the simplest way to delete an object from the Adapter (/AdapterView)
                //Log.d("LIST", "removed object!");
                if(arrayAdapter.getCount()>1)
                   tempList.remove(tempList.get(arrayAdapter.getCount()-1));
                else{
                    tempList.clear();
                    tempList.addAll(al);
                }
                arrayAdapter.notifyDataSetChanged();

            }

            @Override
            public void onLeftCardExit(Object dataObject) {

            }

            @Override
            public void onRightCardExit(Object dataObject) {

            }

            @Override
            public void onAdapterAboutToEmpty(int itemsInAdapter) {
            }
        });

        // Optionally add an OnItemClickListener
        flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
            @Override
            public void onItemClicked(int itemPosition, Object dataObject) {
                //makeToast(ProductDialyActivate.this, "Clicked!");
            }
        });
    }

	public void onReturn(final String value) {// TODO Auto-generated method stub
        System.out.println("coming in onReturn:"+value);
		if(value.isEmpty())
            return;
        lastCode=value;
        if(isLotNumberModel){
            String codeOrReference=value;
            if(codeOrReference.matches(matchPattern))
                productHander.obtainMessage(ProductUtil.MSG_SUCCESS,codeOrReference).sendToTarget();
            else {
                Toast.makeText(getBaseContext(), "与设定规则不匹配，请检查\r\n" + codeOrReference, Toast.LENGTH_SHORT).show();
            }
            return;
        }
		final ProgressDialog dialog = ProgressDialog.show(this, "", 
		        "查旬中，请稍等 …", true, true);
		new Thread(){
			@Override
			public void run(){
				System.out.println("code is:"+value);
				ProductUtil.findProduct(value, isLocalModel, productHander, productDAO, getProductBuilderType());
				dialog.dismiss(); 
			}			
			}.start();  
	}

	public void onCommand(int command,String value) {
	}
	
	protected Handler productHander   = new Handler() {  
		        public void handleMessage (Message msg) {//此方法在ui线程运行   
		            switch(msg.what) {  
		            case ProductUtil.MSG_SUCCESS:  
		              String showSrc=(String) msg.obj;
		              HistoryItem item=new HistoryItem(null,lastCode,showSrc,1.0);
		              historyManager.addHistoryItem(item);	
		              //drawResultPoints(barcode, rawResult);
		      	      handleDecodeInternally(showSrc);
		      	      break;   
		            case ProductUtil.MSG_FAILURE:  
		            	Toast.makeText(getBaseContext(), getString(R.string.msg_no_find_product)+":"+lastCode, Toast.LENGTH_SHORT).show();
		            	// Wait a moment or else it will scan the same barcode continuously about 3 times
		            	break;
		            }  
		        }  
	};
		  
	private void handleDecodeInternally(String value){
        al.add(value);
        tempList.clear();
        tempList.addAll(al);
        arrayAdapter.notifyDataSetChanged();
		//productDialyTxt.setText(value);
	}
		  
	 public int getProductBuilderType(){
			  return ProductUtil.BUILDERTYPE_BASE;
	 }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
